#include "ReLog.hpp"
#include <iostream>
#include <string>
#include <cstring>
#include <cassert>
#include <unistd.h>

#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>

#include <pthread.h>

static void Usage(std::string name)
{
    std::cout << "Usage:\n\t" << name << " server_ip server_port" << std::endl;
}

class UdpClient
{
    public:
    UdpClient(std::string ip,int port)
    :server_Port_((uint16_t)port),server_Ip_(ip),socket_(-1)
    {};
    ~UdpClient(){};
    public:
    static void* recverAndPrint(void* args)
    {
        while(true)
        {
            int socket = *(int*)args;
            char buffer[1024];
            struct sockaddr_in temp;
            socklen_t len = sizeof temp;
            ssize_t s = recvfrom(socket,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&temp,&len);
            if(s>0)
            {
                buffer[s]=0;
                std::cout<<"server echo# "<<buffer<<std::endl;
            }
        }
    }

    void Init()
    {
        socket_ = socket(AF_INET,SOCK_DGRAM,0);
        assert(socket_>0);

        bzero(&server_,sizeof server_);
        server_.sin_family = AF_INET;
        server_.sin_port = htons(server_Port_);
        server_.sin_addr.s_addr = inet_addr(server_Ip_.c_str()); 

        pthread_t t;
        //接收消息
        pthread_create(&t,nullptr,recverAndPrint,(void*)&socket_);
        //发送消息
        std::string buffer;
        while(true)
        {
            std::cerr<<"Please Enter# ";
            std::getline(std::cin, buffer);
            sendto(socket_, buffer.c_str(),buffer.size(),0,
                    (const struct sockaddr *)&server_,sizeof(server_));
        }
        close(socket_);
    }

    private:
    std::string server_Ip_;
    uint16_t server_Port_;
    int socket_;
    struct sockaddr_in server_;

};

// ./udpClient server_ip server_port
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);
    UdpClient client(server_ip,server_port);
    client.Init();
    return 0;
}